<template>
  <div>
    <h1>商品管理</h1>
    <el-form :inline="true">
      <el-form-item label="">
        <el-input v-model="searchForm.shopName" placeholder="请输入商店名称">
        </el-input>
      </el-form-item>
      <el-form-item label="">
        <el-input
          v-model="searchForm.name"
          placeholder="请输入商品名称"
        ></el-input>
      </el-form-item>
      <el-button class="search" type="success" @click="getList()"
        >查询商品</el-button
      >
      <el-button type="primary" @click="addForm = true">新增商品</el-button>
    </el-form>
    <el-table
      ref="multipleTable"
      tooltip-effect="drak"
      style="width: 100%"
      :data="list"
    >
      <el-table-column label="商店名称" prop="shopName"> </el-table-column>
      <el-table-column label="商品图片">
        <template slot-scope="scope">

          <img style="width:80px;height:80px;border:none;" :src="'http://localhost:8081/'+scope.row.img">
          
          </template>
      </el-table-column>
      <el-table-column label="商品名称" prop="name"></el-table-column>
      <el-table-column label="商品描述" prop="description"></el-table-column>
      <el-table-column label="商品价格/元" prop="money"></el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button type="text" @click="getGoods(scope.row.id)"
            >查看详细</el-button
          >
          <el-button type="text" @click="editHandle(scope.row.id)"
            >编辑</el-button
          >
          <el-divider direction="vertical"></el-divider>

          <template>
            <el-popconfirm
              title="这是一段内容确定删除吗？"
              @confirm="delHandle(scope.row.id)"
            >
              <el-button type="text" slot="reference">删除</el-button>
            </el-popconfirm>
          </template>
        </template>
      </el-table-column>
    </el-table>

    <!-- 增加和编辑询问框 -->
    <el-dialog
      title="增加页面"
      :visible.sync="addForm"
      width="800px"
      :before-close="handleClose"
    >
      <el-form
        :model="goods"
        :rules="formRules"
        ref="goods"
        label-width="100px"
        class="demo-editForm"
      >
      <el-form-item label="商品图片"  >
        <el-upload
            ref="upload"
            action=""
            list-type="picture-card"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
            :on-change="UploadImage"
            :limit="1"
            :file-list="fileList"
            :auto-upload="false"
        >
          <i class="el-icon-plus"></i>
          <template #tip>
            <div style="font-size: 12px;color: #919191;">
              单次限制上传一张图片
            </div>
          </template>
        </el-upload>
        <el-dialog v-model="dialogVisible" style="line-height: 0;">
          <img style="width: 100%;height: 100%"  :src="dialogImageUrl" alt="" />
        </el-dialog>
      </el-form-item>

        <el-form-item label="商品名称" prop="name" label-width="150px">
          <el-input
            v-model="goods.name"
            placeholder="请输入商品名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="商店名称" prop="shopName" label-width="150px">
          <el-input
            v-model="goods.shopName"
            placeholder="请输入商品管理中已有的商店"
          ></el-input>
        </el-form-item>
        <el-form-item label="商品早餐" prop="breakfast" label-width="150px">
          <el-input
            v-model="goods.breakfast"
            placeholder="请输入营养早餐"
          ></el-input>
        </el-form-item>
        <el-form-item label="早餐图片"  >
          <el-upload
              ref="upload"
              action=""
              list-type="picture-card"
              :on-preview="handlePictureCardPreview"
              :on-remove="handleRemove"
              :on-change="UploadImageBreakfast"
              :limit="1"
              :file-list="fileList"
              :auto-upload="false"
          >
            <i class="el-icon-plus"></i>
            <template #tip>
              <div style="font-size: 12px;color: #919191;">
                单次限制上传一张图片
              </div>
            </template>
          </el-upload>
          <el-dialog v-model="dialogVisible" style="line-height: 0;">
            <img style="width: 100%;height: 100%"  :src="dialogImageUrl" alt="" />
          </el-dialog>
        </el-form-item>
        <el-form-item label="商品午餐" prop="lunch" label-width="150px">
          <el-input
            v-model="goods.lunch"
            placeholder="请输入营养午餐"
          ></el-input>
        </el-form-item>
        <el-form-item label="午餐图片"  >
          <el-upload
              ref="upload"
              action=""
              list-type="picture-card"
              :on-preview="handlePictureCardPreview"
              :on-remove="handleRemove"
              :on-change="UploadImageLunch"
              :limit="1"
              :file-list="fileList"
              :auto-upload="false"
          >
            <i class="el-icon-plus"></i>
            <template #tip>
              <div style="font-size: 12px;color: #919191;">
                单次限制上传一张图片
              </div>
            </template>
          </el-upload>
          <el-dialog v-model="dialogVisible" style="line-height: 0;">
            <img style="width: 100%;height: 100%"  :src="dialogImageUrl" alt="" />
          </el-dialog>
        </el-form-item>
        <el-form-item label="商品晚餐" prop="dinner" label-width="150px">
          <el-input
            v-model="goods.dinner"
            placeholder="请输入营养晚餐"
          ></el-input>
        </el-form-item>
        <el-form-item label="晚餐图片"  >
          <el-upload
              ref="upload"
              action=""
              list-type="picture-card"
              :on-preview="handlePictureCardPreview"
              :on-remove="handleRemove"
              :on-change="UploadImageDinner"
              :limit="1"
              :file-list="fileList"
              :auto-upload="false"
          >
            <i class="el-icon-plus"></i>
            <template #tip>
              <div style="font-size: 12px;color: #919191;">
                单次限制上传一张图片
              </div>
            </template>
          </el-upload>
          <el-dialog v-model="dialogVisible" style="line-height: 0;">
            <img style="width: 100%;height: 100%"  :src="dialogImageUrl" alt="" />
          </el-dialog>
        </el-form-item>
        <el-form-item label="商品价格/元" prop="money" label-width="150px">
          <el-input
            v-model="goods.money"
            placeholder="请输入商品价格"
          ></el-input>
        </el-form-item>
        <el-form-item label="商品概述" prop="description" label-width="150px">
          <el-input
            v-model="goods.description"
            placeholder="请输入商品概述"
          ></el-input>
        </el-form-item>
        

        <el-form-item class="add">
          <el-button
            v-if="goods.id == undefined"
            type="primary"
            @click="submitForm('goods')"
            >创建</el-button
          >
          <el-button v-else type="primary" @click="submitForm('goods')"
            >更新</el-button
          >
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 查询商品详细页面 -->
    <el-dialog
      title="商品详细页面"
      :visible.sync="searchInfo"
      width="80%"
      :before-close="handleClose"
      class="search_dialog"
    >
      <div class="container">
        <h3>商店详细——{{ goods.shopName }}——{{ goods.name }}</h3>
        <el-carousel :height="bannerHeight+'px'" type="card">
          <el-carousel-item>
            <img :src="'http://localhost:8081/'+goods.img" alt="暂无图片" title="商品图片">
          </el-carousel-item>
          <el-carousel-item>
            <img :src="'http://localhost:8081/'+goods.breakfastimg" alt="暂无图片" title="商品早餐">
          </el-carousel-item>
          <el-carousel-item>
            <img :src="'http://localhost:8081/'+goods.lunchimg" alt="暂无图片" title="商品午餐">
          </el-carousel-item>
          <el-carousel-item>
            <img :src="'http://localhost:8081/'+goods.dinnerimg" alt="暂无图片" title="商品晚餐">
          </el-carousel-item>
          </el-carousel>
        <el-descriptions :column="2">
          <el-descriptions-item label="商品名称">{{
            goods.name
          }}</el-descriptions-item>
          <el-descriptions-item label="商店名称">{{
            goods.shopName
          }}</el-descriptions-item>
          <el-descriptions-item label="营养早餐">{{
            goods.breakfast
          }}</el-descriptions-item>
          <el-descriptions-item label="营养午餐">{{
            goods.lunch
          }}</el-descriptions-item>
          <el-descriptions-item label="营养晚饭">{{
            goods.dinner
          }}</el-descriptions-item>
          <el-descriptions-item label="商店介绍">{{
            goods.shopDescription
          }}</el-descriptions-item>
          <el-descriptions-item label="商品介绍">{{
            goods.description
          }}</el-descriptions-item>
        </el-descriptions>
        <j-comment
          :title="'商品-'+goods.name+'评论'"
          :key-map="keyMap"
          :showNumber="2"
          :comment-datas="commentDatas"
          @submitComment="submitComment"
        >
        </j-comment>
        <div v-if="commentDatas.length == 0" class="remark">
          暂无评论
        </div>
      </div>
      <el-button type="danger" @click="searchInfo = false">关闭</el-button>
    </el-dialog>

    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      layout="total, sizes, prev, pager, next, jumper"
      :page-sizes="[10, 20, 50, 100]"
      :current-page="current"
      :page-size="size"
      :total="total"
    >
    </el-pagination>
  </div>
</template>

<script>
export default {
  name: "Goods",
  data() {
    const isNum = (rule, value, callback) => {
      const price = /^[0-9]*$/;
      if (!price.test(value)) {
        callback(new Error("金额只能为数字"));
      } else {
        callback();
      }
    };
    return {
      fileList:[],
      dialogImageUrl: '',
      dialogVisible: false,
      total: 0,
      size: 10,
      current: 1,
      list: [],
      addForm: false,
      bannerHeight:400,
      searchForm: {
        name: "",
        shopName: "",
      },
      ruleForm: {
        name:'',
        image:'',
        summary:'',
        issue:'',
      },
      keyMap: {
        pid: "pid",
        id: "id",
      },
      searchInfo: false,
      goods: {},
      formRules: {
        name: [
          {
            required: true,
            message: "请输入商品名称",
            trigger: "blur",
          },
        ],
        shopName: [
          {
            required: true,
            message: "请输入商店名称",
            trigger: "blur",
          },
        ],
        breakfast: [
          {
            required: true,
            message: "请输入商品早餐",
            trigger: "blur",
          },
        ],
        lunch: [
          {
            required: true,
            message: "请输入商品午餐",
            trigger: "blur",
          },
        ],
        dinner: [
          {
            required: true,
            message: "请输入商品晚餐",
            trigger: "blur",
          },
        ],
        money: [
          {
            required: true,
            message: "请输入商品价格",
            trigger: "blur",
          },
          {
            validator: isNum,
            message: "价格必须大于0",
            trigger: "blur",
          },
        ],
        description: [
          { required: true, message: "请输入商品概要", trigger: "blur" },
        ],
      },
      commentDatas: []
    };
  },
  methods: {
    getList() {
      this.$axios
        .get("/sys/goods/list", {
          params: {
            name: this.searchForm.name,
            shopName: this.searchForm.shopName,
            current: this.current,
            size: this.size,
          },
        })
        .then((res) => {
          this.list = res.data.data.records;
          this.size = res.data.data.size;
          this.current = res.data.data.current;
          this.total = res.data.data.total;
        });
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$axios
            .post(
              "/sys/goods/" + (this.goods.id ? "update" : "save"),
              this.goods
            )
            .then((res) => {
              this.getList();
              this.resetForm();
              this.$message({
                showClose: true,
                message: res.data.data,
                type: "success",
                onClose: () => {},
              });
            });
          this.addForm = false;
        }
      });
    },
    resetForm() {
      this.addForm = false;
      this.searchInfo = false;
      this.goods = {};
      this.commentDatas = [];
    },
    handleSizeChange(val) {
      this.size = val;
      this.getList();
    },
    handleCurrentChange(val) {
      this.current = val;
      this.getList();
    },
    handleClose() {
      this.resetForm();
    },
    editHandle(id) {
      this.$axios.get("/sys/goods/info/" + id).then((res) => {
        this.goods = res.data.data;
        this.addForm = true;
      });
    },
    seachInfoClose() {
      this.resetForm();
    },
    getGoods(id) {
      this.getComment(id);
      this.$axios.get("/sys/goods/info/" + id).then((res) => {
        this.goods = res.data.data;
        this.searchInfo = true;
      });
    },
    getComment(id){
      this.$axios.get("/goods/comment/info/"+id).then((res)=>{
        this.commentDatas = res.data.data;
        console.log(this.commentDatas);
      });
    },
    selectEmoji(emoji) {
      console.log(emoji);
    },
    /**
     * 表情转码
     * @param {string} str  需要转码的表情
     * @return {string} 转码后的字符串
     */
    utf16toEntities(str) {
      const patt = /[\ud800-\udbff][\udc00-\udfff]/g; // 检测utf16字符正则
      str = str.replace(patt, (char) => {
        let H, L, code, s;
        if (char.length === 2) {
          H = char.charCodeAt(0); // 取出高位
          L = char.charCodeAt(1); // 取出低位
          code = (H - 0xd800) * 0x400 + 0x10000 + L - 0xdc00; // 转换算法
          s = `&#${code};`;
        } else {
          s = char;
        }
        return s;
      });
      return str;
    },
    /**
     * 表情转码
     * @param {string} str  需要转码的表情
     * @return {string} 转码后的字符串
     */
    utf16toEntities(str) {
      const patt = /[\ud800-\udbff][\udc00-\udfff]/g; // 检测utf16字符正则
      str = str.replace(patt, (char) => {
        let H, L, code, s;
        if (char.length === 2) {
          H = char.charCodeAt(0); // 取出高位
          L = char.charCodeAt(1); // 取出低位
          code = (H - 0xd800) * 0x400 + 0x10000 + L - 0xdc00; // 转换算法
          s = `&#${code};`;
        } else {
          s = char;
        }
        return s;
      });
      return str;
    },

    submitComment(item) {
      item['goodId'] = this.goods.id;
      console.log("item: ", item);
      this.$axios.post("/goods/comment/save",item).then((res) =>{
        this.getComment(this.goods.id);
        this.$message({
                showClose: true,
                message: res.data.data,
                type: "success",
                onClose: () => {},
            });
      })
    },
    delHandle(id) {
      this.$axios.get("/sys/goods/delete?id=" + id).then((res) => {
         this.getList();
        this.$message({
          showClose: true,
          message: res.data.data,
          type: "success",
          onClose: () => {
          },
        });
      });
    },
     //上传图片的方法
     UploadImage(file,filelist) {
      //console.log(file);
      let fd = new FormData()
      fd.append('file', file.raw) //传给后台接收的名字 file
      console.log(filelist)
      console.log(file.raw);
      this.$axios.post('/upload/image', fd, {headers: {'Content-Type': 'multipart/form-data',}}).then(res => {
        //上传成功后返回的数据,
        console.log("上传图片到:"+res.data.data);
        // 将图片地址给到表单.
        this.goods.img=res.data.data
      }).catch(e =>{
        this.$message({
          message:"上传失败",
          type:"error"
        })
      })
 
    },
     //上传早餐图片的方法
     UploadImageBreakfast(file,filelist) {
      //console.log(file);
      let fd = new FormData()
      fd.append('file', file.raw) //传给后台接收的名字 file
      console.log(filelist)
      console.log(file.raw);
      this.$axios.post('/upload/image', fd, {headers: {'Content-Type': 'multipart/form-data',}}).then(res => {
        //上传成功后返回的数据,
        console.log("上传图片到:"+res.data.data);
        // 将图片地址给到表单.
        this.goods.breakfastimg=res.data.data
      }).catch(e =>{
        this.$message({
          message:"上传失败",
          type:"error"
        })
      })
 
    },
     //上传午餐图片的方法
     UploadImageLunch(file,filelist) {
      //console.log(file);
      let fd = new FormData()
      fd.append('file', file.raw) //传给后台接收的名字 file
      console.log(filelist)
      console.log(file.raw);
      this.$axios.post('/upload/image', fd, {headers: {'Content-Type': 'multipart/form-data',}}).then(res => {
        //上传成功后返回的数据,
        console.log("上传图片到:"+res.data.data);
        // 将图片地址给到表单.
        this.goods.lunchimg=res.data.data
      }).catch(e =>{
        this.$message({
          message:"上传失败",
          type:"error"
        })
      })
 
    },
    //上传晚餐图片的方法
    UploadImageDinner(file,filelist) {
      //console.log(file);
      let fd = new FormData()
      fd.append('file', file.raw) //传给后台接收的名字 file
      console.log(filelist)
      console.log(file.raw);
      this.$axios.post('/upload/image', fd, {headers: {'Content-Type': 'multipart/form-data',}}).then(res => {
        //上传成功后返回的数据,
        console.log("上传图片到:"+res.data.data);
        // 将图片地址给到表单.
        this.goods.dinnerimg=res.data.data
      }).catch(e =>{
        this.$message({
          message:"上传失败",
          type:"error"
        })
      })
 
    },
    //移除图片功能
    handleRemove(file, fileList) {
      console.log(file, fileList)
 
    },
    //预览图片功能
    handlePictureCardPreview(file) {
      console.log(file.url);
      this.dialogVisible = true
      this.dialogImageUrl = file.url
 
    },
  },

  created() {
    this.getList();
    
  },
};
</script>

<style scoped>
.container h3 {
  margin-left: 50%;
  transform: translateX(-25%);
  margin-top: -20px;
}
.search_dialog {
  margin-left: 10% !important;
}
.has-colon {
  font-weight: 600;
}
.remark{
  margin-left : 50%;
  transform: translateX(-25%);
  color: #ccc;
  font-size : 25px;
}
.el-table {
  font-size: 18px;
}
div /deep/.el-dialog__title {
  font-size: 22px;
}

.el-table,
div /deep/.el-form-item__label,
.el-input {
 font-size: 18px;
}
.el-carousel img{
  margin-left: 70px;
  width: 500px;
  height: 300px;
} 
</style>